package com.lagou.rpc.consumer;


import com.lagou.rpc.consumer.config.StaticVariable;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

@SpringBootApplication
public class ClientBootStrapApplication {

    @Autowired
    private ZkClient zkClient;

    @Value("${zookeeper.grand-path}")
    private String grandPath;

    public static void main(String[] args) {
        SpringApplication.run(ClientBootStrapApplication.class, args);
    }

    @PostConstruct
    public void beforeInit() {
        System.out.println("启动时调用");
        //todo 启动时需要获取zookeeper内部所有的子节点
        if (zkClient.exists(grandPath)) {
            StaticVariable.providerInfoList = zkClient.getChildren(grandPath);
        }
        //todo 需要注册对于grandPath的监听
        //当新的服务上下线时需要往providerList中添加信息
        /*
            客户端可以对一个不存在的节点进行子节点变更的监听
            只要该节点的子节点列表发生变化，或者该节点本身被创建或者删除，都会触发监听
         */
        zkClient.subscribeChildChanges(grandPath, new IZkChildListener() {
            /*
                s : parentPath
                list : 变化后子节点列表
             */
            public void handleChildChange(String parentPath, List<String> list) throws Exception {
                System.out.println(parentPath + "的子节点列表发生了变化,变化后的子节点列表为"+ list);
                StaticVariable.providerInfoList = list;
            }
        });

    }

    // 使用 http://localhost:8080/actuator/shutdown 进行优雅关闭，这样可以触发@PreDestroy回调
    @PreDestroy
    public void beforeShutdown() {
        System.out.println("退出时调用");
    }
}
